<template>
<div style="width:100%;">
  <div class="title">
    目标：{{name}}
    <div class="center">
      X:
      <a-input v-model="x"></a-input>
    </div>
    <div class="center">
      Y:
      <a-input v-model="y"></a-input>
    </div>
    <a-button type="primary" @click="change">更新位置</a-button>
  </div>
  <!-- <h3>X1:{{x1}} Y1:{{y1}}</h3>  -->
  <div id="maps" class="map">
    <div id="popup" class="ol-popup">
      <a href="#" id="popup-closer" class="ol-popup-closer"></a>
      <div id="popup-content" class="popup-content"></div>
    </div>
  </div>
</div>
</template>

<script>
import Point from "ol/geom/Point";
import {
  GeoJSON
} from "ol/format";
import "ol/ol.css";

import {
  Icon,
  Fill,
  Stroke,
  Style
} from "ol/style";
import {
  getCenter
} from "ol/extent";
import {
  defaults as defaultControls
} from "ol/control";

import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import {
  Map,
  View,
  Feature
} from "ol";
import {
  fromLonLat
} from "ol/proj";

// 投影
import {
  transform
} from "ol/proj";
import Overlay from "ol/Overlay";
import {
  updatePoint,
  getPoint
} from "@/api/article.js";
const JSONURl = require("./JSON/2.json");
export default {
  data() {
    return {
      map: null,
      point: null,
      x: null,
      y: null,
      timer: null,

      name: null,

      personIcons: [{
          x: 27.970491535012,
          y: 6871.263035307627,
          name: 1,
          type: "p1.png",
        },
        {
          x: 485.5882702715971,
          y: 1269.2510749397316,
          name: 2,
          type: "p1.png",
        },
        {
          x: 18.7480305399586,
          y: 10292.284252992747,
          name: 3,
          type: "p1.png",
        },
        {
          x: -818.7480305399586,
          y: 10292.284252992747,
          name: 4,
          type: "p.png",
        },
      ],
      // JSONd图层
      vector: null,
      // 图标层
      vectorLayer: null,
      personLayer: null,
      // 图层
      province: null,
      feature: null,
    };
  },
  mounted() {
    this.init();
    //添加JSON底图
    this.addJSON();
    //  添加弹框图层
    this.addPopup();
    // 添加小人图层
    this.personIocn();
    this.setpPosition();
    //添加移动层
  },
  destroyed() {
    this.cl;
  },
  methods: {
    // 初始化地图
    init() {
      let extent = [200, 200, 4000, 200];
      this.map = new Map({
        view: new View({
          center: getCenter(extent),
          zoom: 11,
          // 最大放大倍数
          maxZoom: 14,
          // 最小缩放倍数
          minZoom: 10,
        }),
        // 图层 layers 配置图层的数据源
        layers: [],
        target: "maps",
      });
      // this.map.on("pointermove", (e) => {
      //   // console.log(e.coordinate);
      //   this.x = e.coordinate[0];
      //   this.y = e.coordinate[1];
      //   // this.x1 = transform(e.coordinate, "EPSG:3857", "EPSG:4326");
      // });
    },
    // 切换图标层
    changeImg(a) {
      if (a) {
        this.addIocn(this.Icon);
      } else {
        this.map.removeLayer(this.vectorLayer);
      }
    },
    /**
     * 第一种：点标记 marker
     * 创建一个标注信息
     */
    addMarker() {
      let extent = [2, 5, 40, 20];
      // 绘画图层
      var marker = new Overlay({
        position: getCenter(extent),
        positioning: "center-center",
        element: document.getElementById("marker"),
        stopEvent: false,
      });
      this.map.addOverlay(marker);
    },
    /**
     * 点击弹出框
     */
    addPopup() {
      // 使用变量存储弹窗所需的 DOM 对象
      var container = document.getElementById("popup");
      var closer = document.getElementById("popup-closer");
      var content = document.getElementById("popup-content");
      // 创建一个弹窗 Overlay 对象
      this.overlay = new Overlay({
        element: container, //绑定 Overlay 对象和 DOM 对象的
        autoPan: false, // 定义弹出窗口在边缘点击时候可能不完整 设置自动平移效果
        autoPanAnimation: {
          duration: 250, //自动平移效果的动画时间 9毫秒）
        },
      });

      // 将弹窗添加到 map 地图中
      this.map.addOverlay(this.overlay);
      let _that = this;
      /**
       * 为弹窗添加一个响应关闭的函数
       */
      closer.onclick = function () {
        _that.overlay.setPosition(undefined);
        closer.blur();
        return false;
      };
      /**
       * 添加单击map 响应函数来处理弹窗动作
       */
      this.map.on("click", function (e) {
        // let coordinate = transform(e.coordinate, "EPSG:3857", "EPSG:4326");

        let feature = _that.map.forEachFeatureAtPixel(e.pixel, function (
          feature
        ) {
          return feature;
        });

        if (feature == undefined) {
          _that.overlay.setPosition(undefined);
          closer.blur();
        } else {
          content.innerHTML = feature.get("name");
          // 获取图标的信息
          const point = feature.getGeometry().flatCoordinates;
          _that.x = point[0];
          _that.y = point[1];
          _that.point = point;
          _that.name = feature.get("name");
          // 渲染图层
          // _that.changeJSON(feature);
          // _that.overlay.setPosition(e.coordinate); //把 overlay 显示到指定的 x,y坐标
        }
      });
    },
    // 点击增加图标
    addIocn(con) {
      let arr = [];
      for (let i = 0; i < con.length; i++) {
        let iconFeature = new Feature({
          geometry: new Point([con[i].x, con[i].y]),
          name: `我的标识${i}`,
        });
        let src = require(`./JSON/${con[i].type}`);
        let iconStyle = new Style({
          image: new Icon({
            anchor: [0.5, 0.5],
            src: src,
          }),
        });
        iconFeature.setStyle(iconStyle);
        arr.push(iconFeature);
      }

      this.vectorLayer = new VectorLayer({
        source: new VectorSource({
          features: arr,
        }),
        zIndex: 21,
      });
      this.map.addLayer(this.vectorLayer);
    },

    //计算图表 图形
    getIcon(type) {
      let src = require(`./JSON/${type}`);
      // console.log(src);
      let styleIcon = new Style({
        // 设置图片效果
        image: new Icon({
          src: src,
          anchorXUnits: "pixels",
          anchorYUnits: "pixels",
          imgSize: [200, 200],
          anchor: [1, 1],
        }),
      });
      return styleIcon;
    },
    // 渲染JSON底层
    addJSON() {
      // =====
      let source = new VectorSource({
        features: new GeoJSON().readFeatures(JSONURl),
        // wrapX: false,
        // url: "https://geo.datav.aliyun.com/areas_v2/bound/100000.json",
        // format: new GeoJSON(),
      });

      let styles = new Style({
        stroke: new Stroke({
          width: 3,
          color: "pink",
        }),
        fill: new Fill({
          color: "red",
        }),
      });
      // 绘画图层
      this.vector = new VectorLayer({
        source: source,
        minZoom: 1,
        // projection: "EPSG:4326", //projection 设置地图的投影坐标系统  默认是EPSG:3857
        renderBuffer: 200,
        zIndex: 1,
        style: styles,
      });
      // console.log(fill.getColor());
      // fill.setColor("pink");
      // console.log(fill.getColor());
      // var r3D = new ol.render3D({ height: 10, defaultHeight: 3.5 });
      // this.vector.setRender3D(r3D);
      this.map.addLayer(this.vector);
    },
    // 渲染小人图层
    personIocn() {
      let arr = [];
      for (let i = 0; i < this.personIcons.length; i++) {
        let iconFeature = new Feature({
          geometry: new Point([this.personIcons[i].x, this.personIcons[i].y]),
          name: this.personIcons[i].name,
        });
        let src = require(`./JSON/${this.personIcons[i].type}`);
        let iconStyle = new Style({
          image: new Icon({
            anchor: [0.5, 0.5],
            src: src,
          }),
        });
        iconFeature.setStyle(iconStyle);
        arr.push(iconFeature);
      }

      this.personLayer = new VectorLayer({
        source: new VectorSource({
          features: arr,
        }),
        zIndex: 22,
      });
      this.map.addLayer(this.personLayer);
    },

    // 更新小人位置
    changePerson() {
      try {
        this.map.removeLayer(this.personLayer);
        this.personIocn();
      } catch {
        this.personIocn();
      }
    },
    change() {
      let a = null;
      this.personIcons.filter((item, index) => {
        console.log(this.name, item.name);
        if (this.name == item.name) {
          a = index;
          return true;
        }
      });
      this.personIcons[a].x = this.x;
      this.personIcons[a].y = this.y;
      this.changePerson();
      // updatePoint(this.personIcons[a])
      //   .then((res) => {})
      //   .catch((err) => {
      //     console.log(err);
      //   });
    },
    // 定时跟新位置
    setpPosition() {
      // setInterval(() => {
      //   this.personIcons[3].x = Math.floor(Math.random() * 10000 + 1);
      //   this.personIcons[3].y = Math.floor(Math.random() * 10000 + 1);
      //   this.changePerson();
      // }, 1000);
      try {
        getPoint()
          .then((res) => {
            this.personIcons[3].x = res.x;
            this.personIcons[3].y = res.y;
            this.changePerson();
            this.start();
          })
          .catch((err) => {
            this.start();
          });
      } catch {
        clearTimeout(this.timer); // 清除
        this.start();
      }
    },
    start() {
      let _this = this;
      this.timer = setTimeout(() => {
        _this.setpPosition();
        console.log(11);
      }, 1000);
    },
    // 自定义图形
    changeJSON(pixel) {
      let _this = this;
      let style = new Style({
        stroke: new Stroke({
          color: "#f00",
          width: 1,
        }),
        fill: new Fill({
          color: "rgba(255,0,0,0.1)",
        }),
        text: new Text({
          font: "12px Calibri,sans-serif",
          fill: new Fill({
            color: "#000",
          }),
          stroke: new Stroke({
            color: "#f00",
            width: 3,
          }),
        }),
      });
      this.province = new VectorLayer({
        source: new VectorSource(),
        map: _this.map,
        zIndex: 2,
        style: style,
      });
      // getSource 是获取图层的数据源
      // _this.province.getSource().addFeature(pixel);
      _this.feature = pixel;
    },
  },
};
</script>

<style lang="scss" scoped>
.map {
  width: 100%;
  height: 600px;
}

.ol-popup {
  position: absolute;
  background-color: #ccc;
  -webkit-filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
  filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
  // padding: 15px;
  border-radius: 10px;
  border: 1px solid #cccccc;
  bottom: 12px;
  left: -50px;
}

.ol-popup:after,
.ol-popup:before {
  top: 100%;
  border: solid transparent;
  content: " ";
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
}

.ol-popup:after {
  border-top-color: white;
  border-width: 10px;
  left: 48px;
  margin-left: -10px;
}

.ol-popup:before {
  border-top-color: #cccccc;
  border-width: 11px;
  left: 48px;
  margin-left: -11px;
}

.ol-popup-closer {
  text-decoration: none;
  position: absolute;
  top: 2px;
  right: 8px;
}

.popup-content {
  width: 400px;
}

.ol-popup-closer:after {
  content: "✖";
}

#marker {
  width: 20px;
  height: 20px;
  background: red;
  border-radius: 50%;
}

#textInfo {
  width: 200px;
  height: 40px;
  line-height: 40px;
  background: burlywood;
  color: yellow;
  text-align: center;
  font-size: 20px;
}

.title {
  width: 60%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
